package com.woniu.woniuk16.securityUtil;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.woniuk16.exception.stu.PowerException;
import com.woniu.woniuk16.model.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginErrorHandler implements AuthenticationFailureHandler {

        private ObjectMapper om = new ObjectMapper();

        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
                throws IOException, ServletException {
            response.setCharacterEncoding("utf8");
            response.setContentType("application/json;charset=utf8");
            //result
            Result result = null;
            if (exception instanceof PowerException) {
                result = Result.getInstance(exception.getMessage()).setCode(403).setMessage("没有权限");
            }else {
                result = Result.getInstance(exception.getMessage()).setCode(30000).setMessage("用户名或密码不正确");
            }
            String json = om.writeValueAsString(result);
            response.getWriter().write(json);
            response.getWriter().flush();
        }

    }
